Home > database >  convert JSON to array -flutter
convert JSON to array -flutter

Time:09-22

so im using sql_conn dependency on my flutter project to connect database to my flutter project.

im following the example in the flutter package site and using this method

  var res = "";
  Future<void> cetak(String query) async {
    var req = await SqlConn.readData(query);
    setState(() {
      res = req;
    });
  }

the problem is, res is showing an Stringlike this

[{"CUST_NAME" : "MY NAME"}]

and i just want to show MY NAME later in Text() widget.

How do i parse res so i can get only MY NAME Value

CodePudding user response:

try this, and read more here

import 'dart:convert';
var res = "";
  Future<void> cetak(String query) async {
    var req = await SqlConn.readData(query);
    var parsedJson = jsonDecode(req);
    setState(() {
      res = parsedJson[0]['CUST_NAME'];
    });
  }

CodePudding user response:

Try this once

  var res = "";
  Future<void> cetak(String query) async {
    var req = await SqlConn.readData(query);
    setState(() {
      res =req[0]["CUST_NAME"];
    });
  }

Please try this let me know if it works for you if you need more modification then pls provide me with your print(req) so I can get more ideas and prepare as you want

CodePudding user response:

  /// To read the data from the database.
  ///
  /// The argument [query] must not be null.
  /// The response is in json list format
  /// and can be decoded using json.decode().
  static Future readData(String query) async {
    Map<String, dynamic> args = {
      "query": query,
    };
    try {
      return await _channel.invokeMethod("readData", args);
    } catch (error) {
      rethrow;
    }
  }

The documentation mentions the response will be in json list format. You can easily decode this by using model class fromJSON methods.

Reference: https://docs.flutter.dev/development/data-and-backend/json

  • Related