API give data NULL in first Load - json

I get the data from API and when API calls on the first load of the screen so API gets the data but in response, the data shows the null value, and when I click on hot reload it response shows data from API.
I don't know what happens with API or response.
Please someone help me to understand what happened with the response I also used await but nothing happens.
Here is my code:-
import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/screens/Favorites.dart';
import 'package:mindmatch/screens/Editprofile.dart';
import 'package:getwidget/getwidget.dart';
import 'package:mindmatch/screens/Sidebar.dart';
import 'package:mindmatch/screens/Footer.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mindmatch/utils/Auth.dart';
class Profile extends StatefulWidget {
var usrid;
Profile({Key? key, #required this.usrid}) : super(key: key);
#override
_Profile createState() => _Profile();
}
class _Profile extends State<Profile>{
//SingingCharacter? _character = SingingCharacter.male;
var url;
var data;
final body = null;
#override
Widget build(BuildContext context){
var UsrID = widget.usrid;
final Size size = MediaQuery.of(context).size;
final ThemeData themeData = Theme.of(context);
final double padding = 25;
final sidePadding = EdgeInsets.symmetric(horizontal: padding);
var url = Uri.https('www.******.net', '/mm_api/index.php',{'act':'profile','UsrID': UsrID});
print(url);
// print(getData());
Future getData() async{
final res = await http.get(
url,
headers: {'Content-Type': 'application/json'},
);
//var res = await http.get(Uri.parse('www.*******.net/mm_api/index.php?act=profile&UsrID=${UsrID}'));
print(res);
//data = json.decode(res.body);
data = jsonDecode(res.body);
print(data);
//setState(() {});
//print(res.body);
}
#override
void initState() async{
super.initState();
getData();
// print (await getData());
}
print(data);
//print(getData());
//return SafeArea(
return Scaffold(
appBar: AppBar(
titleSpacing: 3,
backgroundColor: Colors.white,
elevation: 0,
title: Text('My Profile', style: TextStyle(color: Colors.black, fontSize: 15,),),
leading: Builder(
builder: (BuildContext context) {
return Padding(padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
child: IconButton(
icon: SvgPicture.asset(
width: 30,
'assets/images/Menu.svg',
height: 30,
),
onPressed: () { Scaffold.of(context).openDrawer(); },
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
),
);
},
),
actions: <Widget>[
Padding(
padding: sidePadding,
child: Row(
children: [
//Icon(Icons.search, color: Colors.black,),
SvgPicture.asset(
width: 30,
'assets/images/search.svg',
height: 30,
),
],
)
)
],
),
backgroundColor: Color(0xff8f9df2),
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
//colors: const [Color.fromRGBO(132,105,211,1), Color.fromRGBO(93,181,233,1), Color.fromRGBO(86,129,233,1)],
colors: [Colors.white, Colors.white]
),
),
width: size.width,
height: size.height,
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//addVerticalSpace(30),
data != null?Expanded(
child: Padding(
padding: sidePadding,
child: ListView(
physics: BouncingScrollPhysics(),
children: [
Text('${data[0]['name']}')
],
),
)
): const Center(
child: CircularProgressIndicator(),
)
],
),
],
)
),
drawer: Sidebar(),
persistentFooterButtons: [
Footer(usrid:UsrID),
],
);
//);
}
}
When first load screen it shows me a null value:- Here I Print data form response but it shows me a null value
And when I hot reload the screen it shows me the response value:- It shows the value and I comment any print value or hot reload the screen
Data from API:-
[{"id":"1","name":"anni","fulname":"anni ann","mobile":"+15214639870","email":"anni#gmail.com","about":"sdhbsdbcshcbsdhcbsbchsdb\ncbhbchsc","lookfor":"Relationship, Networking","education":"gcnd,2018","work":"dhfjsk,fjskk","politics":"Liberal, Apolitical","religion":"Protestant, Anglican, Hindu","children":"Have + don't want more, Have and want more","interests":"Treking, Sports, Cooking","distance":" 17 ","age":" 20, 60 "}]
when I test API on the browser it shows correct data but does not show in response
WHY?
Please help me to understand this.
I don't know whats going on with the response

It also looks like you are calling initState in your build method. You have to move it out of build method as it is a separate override method.

You have to call setstate after catching data from api
add this line in your getdata() at the end setstate()
setstate() is used to hot reload programatically so in other words when your app update it's state or any information which is used by your app you have to call setstate() function for reflate on your app's ui.
setstate() function call build method one time again and draw whole tree again.
if you have not use setstate then i suggest some code below do this.
final res = await http.get(
url,
headers: {'Content-Type': 'application/json'},
);
//var res = await http.get(Uri.parse('www.*******.net/mm_api/index.php?act=profile&UsrID=${UsrID}'));
print(res);
//data = json.decode(res.body);
dynamic data = jsonDecode(res.body);
print(data);
return data;
//setState(() {});
//print(res.body);
}
//then edit your future builder
FutureBuilder(builder: (context, snapshot) {
if(snapshot.connectionState==ConnectionState.waiting){
//return loader
}else {
if(snapshot.hasData==true){
//update your ui
}else{
//data is null
}
}
}```

Related

how to show Api response after login in flutter?

I successfully got responses from my API, when a user login with his/her correct or incorrect credentials. how can I display those Api responses in my app whether the user put correct /incorrect name, password?
Here is my API response if he put his correct credentials: if he put the wrong credentials the status code will be 0
Suppose I want to print Status and Message. how can I display that in my app?
Here is my function to call Api:
Future<void> login() async {
var jsonResponse = null;
if (passwordontroller.text.isNotEmpty && emailController.text.isNotEmpty) {
List user;
var response = await http.post(
Uri.parse("http://kokokokokokoklogin"),
body: ({
'LoginId': emailController.text,
'Password': passwordontroller.text
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
print(jsonResponse);
Navigator.push(
context, MaterialPageRoute(builder: (context) => Second()));
} else {
print("Wronggooooooooooooooooooooooooooo");
print(response.body);
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Invalid credentials")));
}
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Blank field is not allowed")));
}
}
And here is my textFormField where user will put his/her credentials
TextFormField(
controller:
emailController, //==========================================
decoration: InputDecoration(
labelText: "Email",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.email)),
),
SizedBox(
height: 10,
),
TextFormField(
controller:
passwordontroller, //=========================================
obscureText: true,
decoration: InputDecoration(
labelText: "Password",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.password)),
),
SizedBox(
height: 45,
),
OutlinedButton.icon(
onPressed: () {
login();
},
SecondPage
Convert your response to JSON and get the parts like this, add error handling (for example if JSON conversion fails):
import 'dart:convert';
And where you get the response:
final jsonResponse = jsonDecode(response.body);
final status = jsonResponse["Status"];
final message = jsonResponse["Message"];
If you want to use this in secondPage, create a named route with arguments and pass it to the route, like explained in the documentation. Or even better, use a FutureBuilder to build the widget that needs the response. This way you can also display a progress indicator while login request is being processed.
Finally Manage to solve it
Here what I did
class AfterLoginResPage extends StatefulWidget {
final ApiResponse rresponse;
const AfterLoginResPage({required this.rresponse});
#override
_AfterLoginResPageState createState() => _AfterLoginResPageState();
}
class _AfterLoginResPageState extends State<AfterLoginResPage> {
var responseRef;
// _SecondState(this.responseRef);
#override
Widget build(BuildContext context) {
var tuhin = Text("Status: ${widget.rresponse.status}");
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Status: ${widget.rresponse.status}"),
Text("Message: ${widget.rresponse.message}"),
Text("Name: ${widget.rresponse.userData!.name}"),
Text("encUserId: ${widget.rresponse.userData!.encUserId}"),
// Text("name: ${widget.UserData.name}"),
SizedBox(
height: 50,
),
OutlinedButton.icon(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Home(),
),
);
},
icon: Icon(
Icons.exit_to_app,
size: 18,
),
label: Text("GoTo Home")),
],
),
),
),
);
}
}

parsing JSON file in flutter

I am parsing this type of JSON file in flutter but I am getting error.
initially, I am able to print the whole data in the console but when I want only the name it gives me an error.
bellow in the image for JSON file.
this the code that I wrote for parsing which gives me 1st value of name as "Abul-Abbas" then it throws an error.
import 'package:flutter/material.dart';
import 'package:flutter_appnew/Constants.dart';
import 'package:flutter_appnew/network.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
const URL ='https://xxxx-api.someapp.com/xxx';
class TabData extends StatefulWidget {
#override
_TabDataState createState() => _TabDataState();
}
class _TabDataState extends State<TabData> {
List image = [];
List Name = [];
#override
void initState() {
super.initState();
this.fetchUser();
}
fetchUser() async{
var response = await http.get(URL);
print(response.statusCode);
if(response.statusCode == 200){
var items = json.decode(response.body)[0]['name'];
print(items);
setState(() {
Name = items;
});
}
else{
setState(() {
Name = [];
});
}
}
#override
Widget build(BuildContext context) {
return ListView.separated(
itemCount: Name.length,
itemBuilder: (BuildContext context, int index){
return getCard(context, index);
},
separatorBuilder: (context, index) => Divider(thickness: 2,),
);
}
Widget getCard(BuildContext context, int index){
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Row(
children: [
Container(
height: 60,
width: 60,
decoration: BoxDecoration(
color: Colors.purple,
borderRadius: BorderRadius.circular(30),
image: DecorationImage(
image: NetworkImage('${image[index]}'),
fit: BoxFit.cover,
),
),
),
SizedBox(width: 20,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('${Name[index]}', style: kListTileTextNameStyle,),
],
),
],
),
),
),
);
}
}
and the same is happening with the image I am not able to show it.
please help this is my first time with JSON file parsing.
I can advice you to try to avoid the dynamic type. Your
var items = json.decode(response.body)[0]['name'];
assigns the items to be the type String and the value is "Abul-Abbas". After that you assign Name which is a List to items which is of type String.
What you actually want to do is to add all names to the list (I guess).
So you should do:
response.body.forEach((element) {
Name.add(element["name"]);
});
I also recommend Renaming Name to names.
If you just wanted the first value of your response, then Name should be of type String.

convert data from a csv to a dynamic List (Flutter)

I create an app that loads the CSV file and displays it as a list view, I have used the following example. https://gist.github.com/Rahiche/9b4b2d3b5c24dddbbe662b58c5a2dcd2
The problem is that my List, don't generate rows
I/flutter ( 2158): [[M01, Plastics, 50, NA
I/flutter ( 2158): M02, Plastics, 85, NA
I/flutter ( 2158): M03, Wood, 50, NA
I/flutter ( 2158): M04, Wood, 15, 3
I/flutter ( 2158): M05, Plastics, 50, NA]]
Here is my code
class TableLayout extends StatefulWidget {
#override
_TableLayoutState createState() => _TableLayoutState();
}
class _TableLayoutState extends State<TableLayout> {
List<List<dynamic>> data = [];
loadAsset() async {
final myData = await rootBundle.loadString("assets/ford.csv");
List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () async {
await loadAsset();
//print(data);
}),
appBar: AppBar(
title: Text("Table Layout and CSV"),
),
body: SingleChildScrollView(
child: Table(
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(200.0),
},
border: TableBorder.all(width: 1.0),
children: data.map((item) {
return TableRow(
children: item.map((row) {
return Container(
color:
row.toString().contains("NA") ? Colors.red : Colors.green,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
row.toString(),
style: TextStyle(fontSize: 20.0),
),
),
);
}).toList());
}).toList(),
),
),
);
}
}
and my ford.csv
M01,Plastics,50,NA
M02,Plastics,85,NA
M03,Wood,50,NA
M04,Wood,15,3
M05,Plastics,50,NA
---
i tried the hints from https://pub.dev/packages/csv#-readme-tab- and from
Not viewing Table Layout from a csv in flutter and I have read several csv files
but every time i have the same issues.
what am I doing wrong??
Please help a new flutter developer. ;)
You can copy paste run full code below
I add setState in function loadAsset()
I did not encounter column width issue, if you still have this issue, please try to add column 2 , 3 or shrink width of FixedColumnWidth
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(100.0),
2: FixedColumnWidth(50.0),
},
code snippet
loadAsset() async {
final myData = await rootBundle.loadString("assets/ford.csv");
List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
setState(() {
});
}
working demo
animated gif did not show correct green color,
so I paste final result in second picture
full code
import 'package:flutter/material.dart';
import 'package:csv/csv.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: TableLayout(),
);
}
}
class TableLayout extends StatefulWidget {
#override
_TableLayoutState createState() => _TableLayoutState();
}
class _TableLayoutState extends State<TableLayout> {
List<List<dynamic>> data = [];
loadAsset() async {
final myData = await rootBundle.loadString("assets/ford.csv");
List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
setState(() {
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () async {
await loadAsset();
//print(data);
}),
appBar: AppBar(
title: Text("Table Layout and CSV"),
),
body: SingleChildScrollView(
child: Table(
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(200.0),
},
border: TableBorder.all(width: 1.0),
children: data.map((item) {
return TableRow(
children: item.map((row) {
return Container(
color:
row.toString().contains("NA") ? Colors.red : Colors.green,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
row.toString(),
style: TextStyle(fontSize: 20.0),
),
),
);
}).toList());
}).toList(),
),
),
);
}
}
It's because of different EOL (END OF LINE) characters that are used to terminate a line in file. i.e Some program use '\r\n' while other '\n'.
So to solve the issue you have to consider that. i.e I am using csv package on window os and while reading from a csv file, you should specify eol argument to convert method of the CsvToListConverter().
return CsvToListConverter().convert(csv.data, eol: '\n');
The fast_csv parser is for parsing CSV data.
It is 2.9-4.7 times faster than the csv parser.
If you need to parse large amounts of data, then it will be more efficient.
Line endings are \n, \r\n or \r (no need to configure).
import 'package:fast_csv/fast_csv.dart' as _fast_csv;
void main(List<String> args) {
final res = _fast_csv.parse(_csv);
print(res);
}
final _csv = '''
M01,Plastics,50,NA
M02,Plastics,85,NA
M03,Wood,50,NA
M04,Wood,15,3
M05,Plastics,50,NA
''';
Output:
[[M01, Plastics, 50, NA], [M02, Plastics, 85, NA], [M03, Wood, 50, NA], [M04, Wood, 15, 3], [M05, Plastics, 50, NA]]

How to deal with complex API responses for making cards in Flutter?

I am very new to Flutter and now developing an app that lists restaurants.
I have an API endpoint that returns JSON data. Here it is: https://node.coredes.in/restaurants.
I have already done the layouts. But I don't know how to deal with JSON data. I already tried to do this from examples I got from net.
I want to know how can I use these fields - doc.name, doc.image_gallery[0], doc.location.locality, doc.friday.closing_at.hour, doc.friday.closing_at.minute, to make a list of cards?
Could anyone please help me out with a sample code?
Here is a sample code below, shows how to get the name of restaurants in your JSON file:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
void main() {
runApp(new MaterialApp(
home: new HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String url = "https://node.coredes.in/restaurants/";
List data;
/*onCreate*/
#override
void initState() {
// TODO: implement initState
super.initState();
getJSONData(); //method
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text("my JSON app")),
body: new ListView.builder(
// itemCount: 1,
//itemCount: data==null ? 0 :data.length ,
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
child: new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Card(
child: new Container(
child: new Text(data[index]['name'] ?? ''),
padding: EdgeInsets.all(20),
),
)
],
),
),
);
},
),
);
}
/*method*/ //RT is Future<String>
Future<String> getJSONData() async {
var response = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
print(response.body);
debugPrint(response.body);
setState(() {
var convertDataToJson = json.decode(response.body);
data = convertDataToJson['doc'];
});
return "Success";
}
}
And you can play with data[index]['name']. For example if you want the city you can do something like that data[index]['location']['city'].
So the class model you said, is in order to make your code easy to understand and fast to be reused. Your JSON file have a complex embedded data on it, and it's a little difficult to access this data. So using a class model will be very helpful to get easily, whatever the value you want from it. Let me show you that with a concret example, to know when a restaurant will open and close, you need to go along with this hierarchy doc => opening_times => Sunday => opening_at and the same for the closing time. So let's translate it to our flutter code, if we want to get just the hour value, it will be like data[index]['opening_time']['Sunday']['opening_at']['hour'], and the same for minute value, same for all the rest. In this hierarchy we didn't took so long to arrive to the end, but you're free to imagine in a very big hierarchy, how it will be the situation. Let's return to our case, now let's take the same example and try to use, like you said, a class model instead of a hard coded JSON attributs. Let's write a model class for Restaurant.
class Restaurant {
String name;
String city;
String day;
bool isOpen;
int hourOpen;
int minuteOpen;
// ..
// ..
// The rest of your wanted attributs
Restaurant(
{this.name,
this.city,
this.day,
this.isOpen,
this.hourOpen,
this.minuteOpen});
}
After that, we will write a method, its main goal is to fill our restaurants variable.
Future<String> getRestaurants() async {
var response = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
var convertDataToJson = json.decode(response.body);
data = convertDataToJson['doc'];
List tempRestaurants = new List();
data.forEach((restaurant) => {
tempRestaurants.add(new Restaurant(
name: restaurant['name'],
city: restaurant['location']['city'],
day: 'Sunday',
isOpen: restaurant['opening_times']['Sunday']['is_open_today'],
hourOpen: restaurant['opening_times']['Sunday']['opening_at']
['hour'],
minuteOpen: restaurant['opening_times']['Sunday']['opening_at']
['minute'])),
});
setState(() {
this.restaurants = tempRestaurants;
});
}
Here is how we get data after writing the model.
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text("my JSON app")),
body: new ListView.builder(
itemCount: restaurants == null ? 0 : restaurants.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
child: new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Card(
child: new Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Name: ${restaurants[index].name}"),
Text("City: ${restaurants[index].city}"),
Text("Day: ${restaurants[index].day}"),
Text("IsOpen: ${restaurants[index].isOpen}"),
Text(
"Time: ${restaurants[index].hourOpen}:${restaurants[index].minuteOpen}"),
]),
padding: EdgeInsets.all(20),
),
)
],
),
),
);
},
),
);
}
PS: in this example, I just took Sunday value in every restaurant instance, so that I can show you how easily the access to data has become. But you can create a class model for it, let's say RestaurantDay, and have attributs like dayName, hourOpen, minuteOpen... And after that, you can link it with the logic where we get data.
Try this:
class DemoClass {
String name;
int Id;
DemoClass(this.name, this.Id);
static DemoClass fromJson(Map<String, dynamic> json) {
return DemoClass(json['name'] as String, json['Id'] as int);
}
Map<String, dynamic> toJson(DemoClass instance) =>
<String, dynamic>{
'name': instance.name,
'Id': instance.trackerId
};
static List<DemoClass> fromJsonListStr(String jsonStr){
var list = jsonDecode(jsonStr) as List;
List<DemoClass> myThing = list.map((e) => DemoClass.fromJson(e)).toList();
return myThing;
}
}
Use this to get a list of objects:
var resp = await http.get('http://apicall.com/array',
headers: {"Content-Type": "application/json"});
var ret = DemoClass.fromJsonListStr(resp.body);
return ret;
Use this to get a single object:
var resp = await http.get('http://apicall.com/array',
headers: {"Content-Type": "application/json"});
var data = jsonDecode(resp.body);
var obj = DemoClass.fromJson(data);

How to show CircularProgressIndicator before Flutter App Start?

In my demo app I need to load a 2 JSON file from server. Both JSON has large data in it. I my Flutter app I call the json using Future + async + await than I call to create a widget with runApp. In the body I try to activate a CircularProgressIndicator. It shows appBar and its content as well as empty white page body and 4 or 5 seconds later loads the data in actual body.
My question is I need to show the CircularProgressIndicator first and once the data load I will call runApp(). How do I do that?
// MAIN
void main() async {
_isLoading = true;
// Get Currency Json
currencyData = await getCurrencyData();
// Get Weather Json
weatherData = await getWeatherData();
runApp(new MyApp());
}
// Body
body: _isLoading ?
new Center(child:
new CircularProgressIndicator(
backgroundColor: Colors.greenAccent.shade700,
)
) :
new Container(
//… actual UI
)
You need to put the data/or loading indicator inside a scaffold, show the scaffold everytime whether you have data or not, the content inside you can then do what you want to do.`
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Hello Rectangle',
home: Scaffold(
appBar: AppBar(
title: Text('Hello Rectangle'),
),
body: HelloRectangle(),
),
),
);
}
class HelloRectangle extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.greenAccent,
height: 400.0,
width: 300.0,
child: Center(
child: FutureBuilder(
future: buildText(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return CircularProgressIndicator(backgroundColor: Colors.blue);
} else {
return Text(
'Hello!',
style: TextStyle(fontSize: 40.0),
textAlign: TextAlign.center,
);
}
},
),
),
),
);
}
Future buildText() {
return new Future.delayed(
const Duration(seconds: 5), () => print('waiting'));
}
}
`