How To Handled Exception In Future Builder Using Flutter

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

How To Handled Exception In Future Builder Using Flutter

Handled Exception In Future Builder
Step 1 
We cannot directly remove the time stamp from Handled Exception In Future Builder  but using the intl.dart package we can easily filter the date stamp from time stamp. So open your flutter project’s pubspec.yaml in code .

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.1

Step 2
After done saving the pubspec.yaml file, Open your flutter project root folder in Command Prompt or Terminal and execute flutter pub get command.

flutter pub get


Complete Code For Handled Exception In Future Builder In Flutter
main.dart
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  final String title;
  MyHomePage({this.title});
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  final String uri =
      'https://jsonplaceholder.typicode.com/users_err'; //intentional error

  Future<String> _errorFuture() async {
    var response = await http.get(uri);

    if (response.statusCode == 200) {
      final items = json.decode(response.body).cast<Map<String, dynamic>>();
      String string = items.first;

      return string;
    } else {
      throw Exception('Failed to load internet');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.amber,
          title: Text("Exception in FutureBuilder")),
      body: FutureBuilder<String>(
        future: _errorFuture(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Center(
              child: Text(
                "ERROR: " + snapshot.error.toString(),
              ),
            );
          }
          return Text(snapshot.data);
        },
      ),
    );
  }
}

 

Related Post