dart flutter中如何获取json返回的值并显示在文本widget上

v9tzhpje  于 2022-12-16  发布在  Flutter
关注(0)|答案(2)|浏览(173)

如何显示变量user的值,并将其显示在文本小部件中,下面是源代码。该值已在终端中打印

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)),
      ),
    );
  }
}
h5qlskok

h5qlskok1#

你需要定义一个新的变量,并在你的API响应准备好时更新它,就像这样:

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)),
      ),
    );
  }
}
kyks70gy

kyks70gy2#

可以创建模型类您,

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

并将FutureBuilder用于未来方法

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");
        },
      ),
    );
  }
}

有关使用FutureBuilder的详细信息

相关问题