Add following dependency in pubspec.yaml file:
http: ^0.13.1
table.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(MaterialApp( debugShowCheckedModeBanner: false, title: "Table In Flutter", home: Scaffold( appBar: AppBar( title: Text("Table Tutorial"), ), body: MyAppTable(), ), )); } class MyAppTable extends StatefulWidget { @override _MyAppTableState createState() => _MyAppTableState(); } class _MyAppTableState extends State<MyAppTable> { List<User> list = []; @override void initState() { setState(() { getAllUsers().then((value) => list = value); }); super.initState(); } @override Widget build(BuildContext context) { if (list.length > 0) { return Container( child: DataTable( columns: [ DataColumn(label: Text("ID")), DataColumn(label: Text("NAME")), DataColumn(label: Text("USERNAME")), ], dividerThickness: 2, sortAscending: true, rows: list .map( (e) => DataRow( cells: [ DataCell(Text(e.id.toString())), DataCell(Text(e.name)), DataCell(Text(e.username)), ], ), ) .toList(), ), ); } else { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator( backgroundColor: Colors.red, ), Text("Please wait..."), ], ), ); } } } Future<List<User>> getAllUsers() async { var resp = await http.get(Uri. parse("https://jsonplaceholder.typicode.com/users")); var userObjsJson = jsonDecode(resp.body) as List; List<User> userObjs = userObjsJson.map((userJson) => User.fromJson(userJson)).toList(); return userObjs; } class User { int id; String name; String username; User(this.id, this.name, this.username); User.fromMap(Map<String, dynamic> map) : id = map['id'], name = map['name'], username = map['username']; Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'username': username, }; } factory User.fromJson(dynamic json) { return User( json['id'] as int, json['name'] as String, json['username'] as String); } }
3 comments:
how to handle error. if we get null from server or api in response or some false message how can we display
check the response body in condition and basis of condition you can return the Widget object.
Sir Its not populting data on First time run..
After running i refresh then it display data
Post a Comment