0

I'm learning and trying to add parameters when calling parameters in functions when getting data from the API, but I'm a bit confused about how I call them in widgets.

static Future<Map<String, DataKuliahModel>> getDataKuliah(String smt) async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    await Future.delayed(const Duration(milliseconds: 1000));
    // String responseJson = await rootBundle.loadString('assets/1.json');

    Map<String, DataKuliahModel> finalResult = {};
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/perwalian/get_paket',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );
    final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;
    result.forEach((key, value) {
      DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);
      finalResult.addAll({
        key: dataKuliah,
      });
    });
    return finalResult;
  }

and I want to call him here enter image description here

5
  • what is your smt ? are you already have it ? Commented Nov 24, 2022 at 1:31
  • yes i have it and have made it in the above function when calling api. static Future<Map<String, DataLectureModel>> getDataLecture(String smt) Commented Nov 24, 2022 at 1:33
  • i see your method doesn't use the String smt anywhere. just remove it and call Services.getDataKuliah() without any arguments Commented Nov 24, 2022 at 1:39
  • I use it because I have to call the data in the API based on parameters, because the data from the API is not a list/array. so i call different data api using parameters Commented Nov 24, 2022 at 1:42
  • example: drive.google.com/file/d/1JKYbyslmy5a66VsL00ITLJffTsTNZ1tt/… Commented Nov 24, 2022 at 1:45

2 Answers 2

1

When you declare a function with positional parameters you need to provide those parameters when you call that function.

import 'package:flutter/material.dart';

class Services {
  static Future<String> greeting(String name) async {
    /// this function doesn't need to be Future
    /// but when you call API to get some data it should be a Future

    return 'Hello $name';
  }
}

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(

      /// pass positional parameter to [greeting] here
      future: Services.greeting('Dash'), 
      builder: (context, AsyncSnapshot<String> snapshot) {
        return Center(
          child: Text(snapshot.data ?? 'default'),
        );
      },
    );
  }
}

Result: Hello Dash

In your case smt seems to be an int not a String and you have to pass it as query parameter to http request as follows

static Future<Map<String, DataKuliahModel>> getDataKuliah(int smt) async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    await Future.delayed(const Duration(milliseconds: 1000));
    // String responseJson = await rootBundle.loadString('assets/1.json');

    Map<String, DataKuliahModel> finalResult = {};
    final response = await http.get(
     // Uri.parse(
      //  '$url/auth/mhs_siakad/perwalian/get_paket',
     // ),
        Uri.http(url, '/auth/mhs_siakad/perwalian/get_paket', 
        {'smt':smt}),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );
    final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;
    result.forEach((key, value) {
      DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);
      finalResult.addAll({
        key: dataKuliah,
      });
    });
    return finalResult;
  }

Sign up to request clarification or add additional context in comments.

1 Comment

0

Have you looked at the Uri replace method?

You can do the following:

Uri.parse('$url/auth/mhs_siakad/perwalian/get_paket').replace(queryParameters:{ "smt":"$smt"});  

Update on FutureBuilder:

// Put this outside your build function
Future<Map<String, DataKuliahModel>> DK ; 

// Put this in your initState if you want the future to run on page load or use it for events like onTap 
DK = Service.getDataKuliah(<PARAM>); 

// This is in your build method
FutureBuilder(

future:DK,
builder: (context, snapshot) {
// add wigets to display results here

}

)

4 Comments

no, I just found out instead
Just looking at the screenshot above, you should't call getDataKuliah() in the FutureBuilder directly. You should possibly call it during init state or in an event that is outside the build method and reference that in the FutureBuilder. If you call getDataKuliah() in the FutureBuilder it will run every single time the build method is called.
can you give a simple example. thanks
can you be more complete? I don't really understand the code you provided

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.