Home > Software design >  List View to show the name and Value Flutter, i have added code snippet
List View to show the name and Value Flutter, i have added code snippet

Time:05-01

below code is able to print the data from JSON on console but i'm stuck in implementing the same in List View... Please help i have added my dart files along with link of JSON and i tried doing some changes in main.dart file but i'm unable to do it as the Flutter is new i'm trying this project to understand the concept....

JSON Data Link:
https://api.exchangerate.host/latest?base=USD

**constants.dart code:**
class ApiConstants {
  static String baseUrl = 'https://api.exchangerate.host/latest?base=USD';
}

**api-service.dart code**  
  import 'dart:convert';
    import 'dart:developer';
    
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    
    import 'constants.dart';
    import 'user_model.dart';
    
    class ApiService {
      Future<Welcome?> getUsers() async {
        try {
          var url = Uri.parse(ApiConstants.baseUrl);
          var response = await http.get(url);
          if (response.statusCode == 200) {
            //print(response.body);
            Map<String, dynamic> map = jsonDecode(response.body);
            //print(map["rates"]);
            for (final name in map["rates"].keys) {
              final value = map["rates"][name];
              print('$name,$value'); // prints entries like "AED,3.672940"
I want this data to show in list view... how to modify the code. 
            }
            Welcome _model = Welcome.fromJson(map);
            return _model;
          }
          return null;
        } catch (e) {
          log(e.toString());
        }
      }
    }

**Main.dart file..** 

import 'package:flutter/material.dart';

import 'api_service.dart';
import 'user_model.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Material App',
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  late List<String>? rateModel = [];
  @override
  void initState() {
    super.initState();
  }

  Future<Welcome> _getData() async {
    Welcome? welcome = (await ApiService().getUsers());
    welcome!.rates.entries
        .map((entry) => rateModel!.add("${entry.key}: ${entry.value}"));

    return welcome;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('REST API Example'),
      ),
      body: /*const Center(
              child: CircularProgressIndicator(),
            )*/
          FutureBuilder<Welcome>(
              future: _getData(),
              builder: (context, snapshot) {
                // print("FutureBuilder $rateModel");
                return ListView.builder(
                  itemCount: rateModel!.length,
                  itemBuilder: (context, index) {
                    return Card(
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Text(rateModel![index].ma),
                              //Text(_userModel![index].),
                            ],
                          ),
                          const SizedBox(
                            height: 20.0,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              //Text(_userModel![index].date),
                              //Text(_userModel![index].website),
                            ],
                          ),
                        ],
                      ),
                    );
                  },
                );
              }),
    );
  }
}

CodePudding user response:

Share your model code for better understanding.

CodePudding user response:

snapshot has data for API call, before using it, check that it is already received like this:

      FutureBuilder<List<...>>(
        future: <api call which returns list>,
        builder: (context, snapshot) {
          return snapshot.hasData 
            ? ListView.builder(
                itemCount: snapshot.data?.length,
                itemBuilder: (context, index) {
                  final item = snapshot.data![index]
                  return <your widget>
                }
              ) 
            : const Text("Loading");
        }
...
  • Related