0

I am really new to flutter and I wonder if it might be possible to load a JSON string into a listview widget without creating a model for it. I mean the JSON itself has an array, call it fields. And this arras has the field as object in it. But I don’t won’t to recreate or append the model all the time, when a new field is present, just use it right away in the code.

Many tutorials use something like json to dart, to create the model but I can’t find some tutorials that show how it would be possible without the model. Maybe because it is a bad design decision? Hoping for your input. Thanks a lot.

1
  • Refer my answer here and here Commented Sep 27, 2022 at 9:31

1 Answer 1

0

Sure you can do it. Just work directly with the result of jsonDecode. But I recommend just creating a model

Example:

import 'dart:convert';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

String json =
    '{"fields":[{"name":"A","age":1},{"age":2},{"name":"C"},{"name":"D","age":4}]}';

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final decoded = jsonDecode(json);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: ListView.builder(
          itemCount: decoded['fields'].length,
          itemBuilder: (context, index) => ListTile(
            title: Text(decoded['fields'][index]['name'] ?? 'No name'),
            trailing: Text(decoded['fields'][index]['age']?.toString() ?? 'No age'),
          ),
        ),
      )),
    );
  }
}

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.