Home > Back-end >  Pushing data to a details screen from a JSON API in Flutter
Pushing data to a details screen from a JSON API in Flutter

Time:10-08

I'm making a simple app that takes data from a JSON API and displays it as a list, and ability to view details in a new page. I want to pass data from a selected listview into a details screen. How do I do it in Flutter and how should I implement it?

My code:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MaterialApp(
    home: Home(),
  ));
}


class Home extends StatelessWidget {
  
  final String apiUrl = "https://reqres.in/api/users?per_page=15";
  Future<List<dynamic>> _fetchDataUsers() async {
    var result = await http.get(Uri.parse(apiUrl));
    return json.decode(result.body)['data'];

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Get HTTP JSON'),
      ),
      body: Container(
        child: FutureBuilder<List<dynamic>>(
          future: _fetchDataUsers(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                  padding: EdgeInsets.all(10),
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    return ListTile(
                      leading: CircleAvatar(
                        radius: 30,
                        backgroundImage:
                        NetworkImage(snapshot.data[index]['avatar']),
                      ),
                      title: Text(snapshot.data[index]['first_name']   " "   snapshot.data[index]['last_name']),
                      subtitle: Text(snapshot.data[index]['email']),
                      onTap: () {Navigator.push(context, MaterialPageRoute(builder: (context) => Details()),);},
                    );
                  });
            } else {
              return Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}

class Details extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }

}

CodePudding user response:

You can simply pass any data like this,

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MaterialApp(
    home: Home(),
  ));
}


class Home extends StatelessWidget {
  
  final String apiUrl = "https://reqres.in/api/users?per_page=15";
  Future<List<dynamic>> _fetchDataUsers() async {
    var result = await http.get(Uri.parse(apiUrl));
    return json.decode(result.body)['data'];

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Get HTTP JSON'),
      ),
      body: Container(
        child: FutureBuilder<List<dynamic>>(
          future: _fetchDataUsers(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                  padding: EdgeInsets.all(10),
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    return ListTile(
                      leading: CircleAvatar(
                        radius: 30,
                        backgroundImage:
                        NetworkImage(snapshot.data[index]['avatar']),
                      ),
                      title: Text(snapshot.data[index]['first_name']   " "   snapshot.data[index]['last_name']),
                      subtitle: Text(snapshot.data[index]['email']),
                      onTap: () {Navigator.push(context, MaterialPageRoute(builder: (context) => Details(detail:snapshot.data[index])),);},
                    );
                  });
            } else {
              return Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}

class Details extends StatelessWidget {
final dynamic detail;

  const Details({Key key, this.detail}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    print(detail);
    // TODO: implement build
    throw UnimplementedError();
  }

}

Better to create model class instead of using dynamic type

If you use routing arguments you can follow this way.

flutter navigation argument

CodePudding user response:

Make constructor in details screen it take object and pass data to it when you make navigator

  • Related