Home > Enterprise >  Flutter/Dart Logic for assigning an API Future's return value to another variable/function
Flutter/Dart Logic for assigning an API Future's return value to another variable/function

Time:07-07

I think my lack of in-depth oop or async/wait knowledge may be hurting me here but I could not seem to find a working solution for myself. Please be kind.

Creating a basic countdown app for which I'm avoiding hard-coding the end-date but instead calling the data from my Flask API server so that I could make changes remotely when needed. Data is a simple Json key/value pair like {"dDate": '2012-02-27 13:27:00'}.

My goal is to receive that string API value and use it with DateTime.parse like below

DateTime myTime = DateTime.parse(dDate);

From there I'll use the myTime DateTime value to do additional calculations like below

class _TimerAppState extends State<TimerApp> {
  static const duration = Duration(seconds: 1);

  int timeDiff = myTime.difference(DateTime.now()).inSeconds;

Once timeDiff is calculated, then its value will be displayed on my Widget.

Where I'm struggling is transforming the following Future instance into a string that I can use. The following is what I've done so far.

Future<String> fetchDDate() async {
  var dateUrl = 'my localhost addr';
  var dateresponse = await http.get(Uri.parse(dateUrl));
  var datedata = await jsonDecode(dateresponse.body);
  var datewelcome = await datedata['dDate'];
  // print(datewelcome);
  return datewelcome;
  }

How should I go about getting fetchDDate()'s value into my DateTime like DateTime myTime = DateTime.parse(fetchDDate());

I appreciate any guidance.

CodePudding user response:

Hoping this helps you to set up the whole scenario.

Let's assume this is your API call method

Future<String> fetchDDate() async {
    await Future.delayed(const Duration(seconds: 2));
    return "2012-02-27 13:27:00";
}

Then wrap it with a meaningful function

Future<int> calculateDiff() async {
  var dDate = await fetchDDate();
  return DateTime.parse(dDate).difference(DateTime.now()).inSeconds;
}

And finally, let's use with widget

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

  @override
  State<DateSampleWidget> createState() => _DateSampleWidgetState();
}

class _DateSampleWidgetState extends State<DateSampleWidget> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: FutureBuilder<int>(
              future: calculateDiff(),
              builder: ((context, snapshot) {
                if (snapshot.hasData) {
                  return Text("${snapshot.data ?? 0}");
                } else if (snapshot.hasError) {
                  return const Text("Something went wrong");
                } else {
                  return const Text("Calculating...");
                }
              })),
        ),
      ),
    );
  }
}

Try a live sample, link

CodePudding user response:

You can simply do

final dateString = await fetchDDate();
final myTime = DateTime.parse(dateString);

from within some other async function.

  • Related