Home > Enterprise >  How to get value returned from json and let it display on text widget in flutter
How to get value returned from json and let it display on text widget in flutter

Time:12-07

How can i display the value from the variable user and display it in the text widget, here the source code below. The value already printed in the terminal

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

class Home extends StatefulWidget {
  const Home({Key key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
//get valueID => null;
  @override
  void initState() {
    super.initState();
    getStringValuesSF();
  }

  getStringValuesSF() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    var stringValue = prefs.getString('currentUserId');

    String apiurl = "http://192.168.161.144/api/dash.php";
    var response = await http.post(Uri.parse(apiurl), body: {
      "userid": stringValue,
    });

    if (response.statusCode == 200) {
      var data = json.decode(response.body);

      if (data["success"] == true) {
        String user;
        String userpics;
        user = data["uname"];
        userpics = data["upic"];

        print(user);
        print(userpics);
      } else if (data["success"] == '10') {
        print('not connected from DB');
      }
    } else {
      print('not connected');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("HomePage")),
      body: Container(
        child: Text("Welcome User", style: TextStyle(color: Colors.black)),
      ),
    );
  }
}

CodePudding user response:

You need to define new variable and update it when ever your api response get ready, like this:

class _HomeState extends State<Home> {

  String userName = "";
  @override
  void initState() {
    super.initState();
    getStringValuesSF();
  }

  getStringValuesSF() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    var stringValue = prefs.getString('currentUserId');

    String apiurl = "http://192.168.161.144/api/dash.php";
    var response = await http.post(Uri.parse(apiurl), body: {
      "userid": stringValue,
    });

    if (response.statusCode == 200) {
      var data = json.decode(response.body);

      if (data["success"] == true) {
        String userpics;

        userpics = data["upic"];

        setState(() {
          userName = data["uname"];
        });
        print(userName);
        print(userpics);
      } else if (data["success"] == '10') {
        print('not connected from DB');
      }
    } else {
      print('not connected');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("HomePage")),
      body: Container(
        child: Text("Welcome User = $userName",
            style: TextStyle(color: Colors.black)),
      ),
    );
  }
}

CodePudding user response:

You can create a model class,

class UserModel {
  final String user;
  final String userpics;
  UserModel({
    required this.user,
    required this.userpics,
  });
   /// add fromJson will be better, skipping for now
}

And use FutureBuilder for future method

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Future<UserModel?> getStringValuesSF() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    var stringValue = prefs.getString('currentUserId');

    String apiurl = "http://192.168.161.144/api/dash.php";
    var response = await http.post(Uri.parse(apiurl), body: {
      "userid": stringValue,
    });

    if (response.statusCode == 200) {
      var data = json.decode(response.body);

      if (data["success"] == true) {
        String user;
        String userpics;
        user = data["uname"] ?? "";
        userpics = data["upic"] ?? "";

        print(user);
        print(userpics);
        return UserModel(user: user, userpics: userpics);
      } else if (data["success"] == '10') {
        print('not connected from DB');
      }
    } else {
      print('not connected');
    }
  }

  late final future = getStringValuesSF();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<UserModel?>(
        future: future,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final user = snapshot.data;
            return Column(
              children: [
                Text(user?.user?? ""),
              ],
            );
          }

          if (snapshot.hasError) return Text("Got error");
          return Text("Other state");
        },
      ),
    );
  }
}

More about using FutureBuilder

  • Related