-
Notifications
You must be signed in to change notification settings - Fork 1
Widgets in Flutter : 3
For this task in addition to your previous widgets, you will be needing
- GestureDetector
- FutureBuilders
- Async functions
To fetch data from an API you would be this code snippet
void showStuff() async {
Map data = await getWeather(apiID,defaultCity);
print(data.toString());
}
Future<Map> getWeather(String apiId, String city) async {
String apiURL = 'https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiId&units=metric';
http.Response response = await http.get(apiURL);
print(json.decode(response.body));
return json.decode(response.body);
}
It fetches the data as Response and returns the JSON as a Map object which is recieved in function showStuff()
and response is loaded into data
If you notice that when you are fetching data, your code initially has nothing to render on screen so you get a red error screen, now you need to build the data at runtime so that live data can be displayed to the User
We use FutureBuilder for this purpose.
Widget displayData()
{
return new FutureBuilder(future: getWeather(apiID, _cityEntered == null ? defaultCity : _cityEntered) ,
builder: (BuildContext context, AsyncSnapshot<Map> snapshot){
if(snapshot.hasData)
{
return ....
}
}
}
TextFormField is used to take input from the user which is used by TextEditingController which together is used to take input from the user. The input is typed into the TextFormField and the controller is used to manage the data input into the textfield
static TextEditingController _cityFieldController = new TextEditingController();
final searchfield = new TextFormField(
decoration: new InputDecoration(
hintText: 'Enter City',
),
autofocus: false,
controller: _cityFieldController,
style: TextStyle(fontFamily: "Quantico"),
);
Gesture Detectors are used to identify the type of user input provided by touch, tap or simulation
GestureDetector(
child: Container(child:Icon(Icons.search)),
onLongPress: (){
_cityFieldController = new TextEditingController(text:defaultCity); //Resets on long press
},
onTap: (){ //On single tap, searches..
setState(() {
_cityEntered = _cityFieldController.text; //Sets City to input
});
build(context); //Rebuilds UI
},
)
Links :