Flutter 中的 MYSQL

Posted

技术标签:

【中文标题】Flutter 中的 MYSQL【英文标题】:MYSQL in Flutter 【发布时间】:2020-09-06 18:30:56 【问题描述】:

我已经在 mysql 服务器上创建了一个数据库,现在我想读取表中存在的所有数据并在 Flutter 的 Listview 中取消它,现在我可以读取所有数据并将其显示在控制台上但无法解析数据到 Listview。

Future<List<ItemCategory>> getCategory() async 
try 
  http.Response response = await http.post(
      "https://***************.000webhostapp.com/*************.php",
  );
  print('getCategory Response: $response.body');
  if (response.body != null) 
    List<ItemCategory> list = parseResponse(response.body);
    return list;
   else 
    return List<ItemCategory>();
  
 catch (e) 
  return List<ItemCategory>(); // return an empty list on exception/error

  

  List<ItemCategory> parseResponse(String responseBody) 
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<ItemCategory>((json) => ItemCategory.fromJson(json)).toList();
  

这是我正在尝试的颤振代码。

这里是 Category 类

class ItemCategory
  int catID;
  String catName, catDesc;
  bool matched = false;

  ItemCategory(this.catID, this.catName, this.catDesc);



   factory ItemCategory.fromJson(Map <String, dynamic> json)
     return ItemCategory(
       catID: json['cat_id'] as int,
       catName: json['cat_name'] as String,
       catDesc: json['cat_desc'] as String
     );
   

【问题讨论】:

您能否展示一个 API 响应示例? 【参考方案1】:

您可以在下面复制粘贴运行完整代码 您可以检查response.statusCode并使用itemCategoryFromJson解析并使用FutureBuilder显示

String jsonString = '''
      ["cat_id":"2","cat_name":"PAKISTANI","cat_desc":"","cat_id":"3","cat_name":"INDIAN","cat_desc":"","cat_id":"4","cat_name":"abc","cat_desc":"","cat_id":"5","cat_name":"def","cat_desc":"","cat_id":"6","cat_name":"hi","cat_desc":""]
      ''';
http.Response response = http.Response(jsonString, 200);
print('getCategory Response: $response.body');
if (response.statusCode == 200) 
  return itemCategoryFromJson(response.body);
  ...

工作演示

完整代码

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

List<ItemCategory> itemCategoryFromJson(String str) => List<ItemCategory>.from(
    json.decode(str).map((x) => ItemCategory.fromJson(x)));

String itemCategoryToJson(List<ItemCategory> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ItemCategory 
  String catId;
  String catName;
  String catDesc;

  ItemCategory(
    this.catId,
    this.catName,
    this.catDesc,
  );

  factory ItemCategory.fromJson(Map<String, dynamic> json) => ItemCategory(
        catId: json["cat_id"],
        catName: json["cat_name"],
        catDesc: json["cat_desc"],
      );

  Map<String, dynamic> toJson() => 
        "cat_id": catId,
        "cat_name": catName,
        "cat_desc": catDesc,
      ;


void main() 
  runApp(MyApp());


class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  


class MyHomePage extends StatefulWidget 
  MyHomePage(Key key, this.title) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
  Future<List<ItemCategory>> _future;

  Future<List<ItemCategory>> getCategory() async 
    try 
      //http.Response response = await http.post(
      // "https://***************.000webhostapp.com/*************.php",
      // );

      String jsonString = '''
      ["cat_id":"2","cat_name":"PAKISTANI","cat_desc":"","cat_id":"3","cat_name":"INDIAN","cat_desc":"","cat_id":"4","cat_name":"abc","cat_desc":"","cat_id":"5","cat_name":"def","cat_desc":"","cat_id":"6","cat_name":"hi","cat_desc":""]
      ''';
      http.Response response = http.Response(jsonString, 200);
      print('getCategory Response: $response.body');
      if (response.statusCode == 200) 
        return itemCategoryFromJson(response.body);
       else 
        return List<ItemCategory>();
      
     catch (e) 
      return List<ItemCategory>(); // return an empty list on exception/error
    
  

  @override
  void initState() 
    _future = getCategory();
    super.initState();
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<List<ItemCategory>> snapshot) 
              switch (snapshot.connectionState) 
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) 
                    return Text(
                      '$snapshot.error',
                      style: TextStyle(color: Colors.red),
                    );
                   else 
                    return ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (context, index) 
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(
                                      snapshot.data[index].catId,
                                    ),
                                    Spacer(),
                                    Text(
                                      snapshot.data[index].catName,
                                    ),
                                  ],
                                ),
                              ));
                        );
                  
              
            ));
  

【讨论】:

【参考方案2】:

所以,这个网站可以帮助你很多Json to Dart。您需要创建一个列表视图构建。

ListView.builder(
  itemCount: 2,
  itemBuilder: (context, i) 
    return list[i]
      ? ListTile(
          var item = list[i];
          title: Text(item.title),
        )
      : Container();
   ,
)

【讨论】:

以上是关于Flutter 中的 MYSQL的主要内容,如果未能解决你的问题,请参考以下文章

如何去除 Flutter 中的“XMLHttpRequest 错误”? (Django 后端,Flutter 前端)

Flutter 中的 pushReplacementNamed 和 popAndPushNamed 有啥区别?

Flutter 中的 shrinkWrap 属性有啥作用?

“flutter doctor”命令找不到安装在 Android Studio 中的 Flutter 和 Dart 插件

Flutter 中的路由

Flutter中的Timer