ARLEQUINA
ARLEQUINA

Reputation: 139

Flutter BLoC 'Future<String>' is not a subtype of type 'String'

currently I'm trying to fetch data from API in BLoC pattern. But after the call, it's throwing this message. 'Future' is not a subtype of type 'String'

Here is the relevanted codes.

Bloc

Stream<NewsState> mapEventToState(NewsEvent event) async* {
    if (event is FetchNews) {
      yield event.isFeatured == true
          ? NewsFeaturedLoading()
          : NewsCommonLoading();

      try {
        print("http req->" + event.isFeatured.toString());
        final List<News> newsList =
            await _fetchNews(event.isFeatured, userRepository.getToken());

        yield event.isFeatured == true
            ? NewsFeaturedSuccess(newsList: newsList)
            : NewsCommonSuccess(newsList: newsList);
      } catch (error) {
        print(error);
        yield event.isFeatured == true
            ? NewsFeaturedFailure(error: error.toString())
            : NewsCommonFailure(error: error.toString());
      }
    }
  }
}

HttpCall

Future<List<News>> _fetchNews(isFeatured, accessToken) async {
  print("before httprequest->>" + accessToken);
  final http.Response response = await http.post(
    Uri.parse(Constant.baseUrl + "/api/news"),
    headers: {
      'Content-type': 'application/json',
      'Accept': 'application/json',
      "x-access-token": "Bearer " + accessToken,
    },
    body: {
      "isFeatured": isFeatured,
    },
  );

  print("response->>>>" + response.body);
  if (response.statusCode == 200) {
    print("news-> " + response.body);
    var obj = json.decode(response.body);
    final data = obj["data"] as List;
    return data.map((rawPost) {
      return News(
        id: rawPost['_id'],
        title: rawPost['Title'],
        content: rawPost['Description'],
      );
    }).toList();
  } else {
    throw Exception(json.decode(response.body));
  }
}

View

SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: Column(
                children: <Widget>[
                  SizedBox(height: 25.0),
                  Align(
                    alignment: Alignment.topLeft,
                    child: Padding(
                      padding: EdgeInsets.only(left: 19.0),
                      child: Text("Common news",
                          style: Constant.newsCommonTextStyle),
                    ),
                  ),
                  if (state is NewsCommonLoading) CircularProgressIndicator(),
                  if (state is NewsCommonSuccess) CommonNews(),
                  if (state is NewsCommonFailure)
                    Text(state.error, style: TextStyle(color: Colors.red)),
                ],
              ),
            ),

Where does this exception come from? And how can I prevent from this kind of exception? Thank you for your help!

Upvotes: 1

Views: 1510

Answers (1)

Rohan Thacker
Rohan Thacker

Reputation: 6357

As you mentioned in the comment userRepository.getToken() is an async function so the return value will be Future.

In Dart every function with the async keyword will have the return value of Future<T>.

To obtain the value of a Future and not the Future itself, two methods are provided.

  1. then() - Call this function after the async function to get the value.
  2. await - Add this keyword before and async function to get the value

Update your code to await userRepository.getToken() to get the String value

Upvotes: 3

Related Questions