How do I create a function to call JSON data on a specific page? The value of the JSON data will be used to be put in the TextField.
I have created the model class and the API for the User data. I want to use the id and the code.
user.dart
import 'dart:convert';
List<User> userFromJson(String str) => List<User>.from(json.decode(str).map((x) => User.fromJson(x)));
String userToJson(List<User> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class User {
User({
....
user-api.dart
import '../model/user.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
Future<List<User>> fetchUser() async{
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var loginID = sharedPreferences.getString('user');
var url = Uri.parse("https:wahatever-abc/user.php?LoginID=$loginID");
final response = await http.get(url);
return userFromJson(response.body);
}
I want to create a function to call the JSON data in a new page call new_user.dart. The data in the function will be used in the Textfield form. I have no idea on how to call it.
new_user.dart
import 'model/user.dart';
import 'api/user-api.dart';
import 'package:http/http.dart' as http;
@override
void initState() {
fetchUserA();
super.initState();
_myActivity = '';
_myActivityResult = '';
}
void fetchUserA() async {
....
}
How do I create and pass the value inside the fetchUser?
What I want to achieve is how do I call the value from the JSON and declare it in the fetchUserA function by using the 'fetchUser()' in the 'user-api.dart' With the called value in the fetchUserA i will use the data to insert it in the Textfield form which i will create it later.
This is what i tried before but its not working. So I wanted to try other way. What I mean by other way is try to do like this this example
Widget build(BuildContext context){
return Form(
key: _formKey,
autovalidateMode: AutovalidateMode.always,
child: FutureBuilder(
future: fetchUser(),
builder: (context, snapshot){
return ListView.builder(
itemCount: snapshot.data.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, index)
{
User user = snapshot.data[index];
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
decoration : InputDecoration(labelText: "${user.id}"),
controller: id,
),
),
),