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.

fisi-pjm
  • 378
  • 2
  • 16

1 Answers1

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

Ivo
  • 18,659
  • 2
  • 23
  • 35