Getting "Missing concrete implementation of State.build" Error in Flutter - flutter

I am receiving the error "Missing concrete implementation of State.build" when attempting to run this code for Angela Yu's FLutter course:
import 'package:flutter/material.dart';
import 'package:clima/services/location.dart';
import 'package:http/http.dart';
class LoadingScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _LoadingScreenState();
}
}
class _LoadingScreenState extends State<LoadingScreen> {
#override
void initState() {
super.initState();
getLocation();
}
}
void getLocation() async {
Location location = Location();
await location.getCurrentLocation();
print(location.latitude);
print(location.longitude);
}
void getData() async {
Response response = await get(
'https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=439d4b804bc8187953eb36d2a8c26a02');
print(response);
#override
Widget build(BuildContext context) {
return Scaffold();
}
}
I have tried the responses related to this question:
missing concrete implementation of state.build
...but have not had any success. Any insight as to what I'm doing wrong would be very much appreciated.

enter code hereYou have a extra } after
#override
void initState() {
super.initState();
getLocation();
}
Delete it
And another missed above
#override
Widget build(BuildContext context) {
return Scaffold();
}
Check your { }

Check your {}. This error mainly comes due to the missing of {} or using extra {}.

Related

I have migrated to null-safety (2.15.1) and this problem still persists

I get the error below when I compile the app.
The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#73713):
The method 'call' was called on null.
Receiver: null
Tried calling: call(Instance of 'ChangeNotifierProvider<UserLoggedIn>')
The error points me to the 'MyApp' part of the code and so I have no idea how to tackle this one.
My app ran with no error before migrating.
This is a part of my code where the cause for this error is.
I went through the code with and I can't find a possible syntax error.
void main() {
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatefulHookWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _amplifyConfigured = false;
bool checkAuthStatus = false;
late AmplifyAuthCognito auth;
var userLoggedIn;
var useProvider;
#override
void initState() {
// TODO: implement initState
super.initState();
_configureAmplify();
}
void _configureAmplify() async {
if (!mounted) return;
auth = AmplifyAuthCognito();
await Amplify.addPlugin(auth);
try {
await Amplify.configure(amplifyconfig);
} on AmplifyAlreadyConfiguredException {
print('Already configured');
}
try {
getUserStatus();
setState(() {
_amplifyConfigured = true;
});
} catch (e) {
print(e);
}
}
#override
Widget build(BuildContext context) {
userLoggedIn = useProvider(userLoggedInProvider);
```
Riverpod removed useProvider in version 1.0.0. As described in the migration guide, you will need to use StatefulHookConsumerWidget instead of StatefulHookWidget to access that same functionality in the newest version:
class MyApp extends StatefulHookConsumerWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends ConsumerState<MyApp> {
// ...
#override
Widget build(BuildContext context) {
userLoggedIn = ref.watch(userLoggedInProvider);
// ...

Get(Uri.http) does not working in flutter when get WorldTime API

i start studying Flutter.
I got a problem when i tried to get Worl Time Api.
Please help me to solve it. Thank a lot.
Here is my code:
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Future getTime() async {
Response response =
await get(Uri.http('worldtimeapi.org', '/api/timezone/Asia/Bangkok'));
print('xx');
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('World Time'),
),
);
}
}
System stuck in Response row, it did not run Print();
enter image description here
Calling getTime function in initState(){} like this:
Future getTime() async {
print('hi');
try {
Response response =
await get(Uri.http('worldtimeapi.org', '/api/timezone/Asia/Bangkok'));
} catch (e) {
print(e);
}
print('xx');
}
#override
void initState() {
getTime();
super.initState();
}
if it not working, check your emulator internet.

Flutter WorkManager Background Fetch Example With StateFull Widget

I have a function called control in the StateFull Widget. I want to run this function with WorkManager every 15 minutes.
How can I call the control function from the callbackDispatcher function?
I added a Stream statically to the Statefull widget and then listened to it but it didn't work.
HomeScreen.dart file
import 'package:flutter/material.dart';
import 'package:workmanager/workmanager.dart';
const taskKontrol = "control";
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Container();
}
#override
void initState() {
super.initState();
setupWorkManager();
}
void control() async
{
//... my code control is here
}
}
void setupWorkManager() async {
await Workmanager.initialize(callbackDispatcher, isInDebugMode: true);
Workmanager.registerPeriodicTask(taskKontrol, taskKontrol,
frequency: Duration(seconds: 10),
existingWorkPolicy: ExistingWorkPolicy.append
);
}
void callbackDispatcher() {
Workmanager.executeTask((taskName, inputData) async {
switch(taskName)
{
case taskKontrol:
// How can I call the control function from here?
print("control from workmanager");
break;
}
return Future.value(true);
});
}
For those who still looking for an answer:
From the official docs:
The callbackDispatcher needs to be either a static function or a top level function to be accessible as a Flutter entry point.
I had this same problem and I solved it by moving the function callbackDispatcher to the file: main.dart
Also, the code that initializes callbackDispatcher must be in main() before the App() widget loads.
To call your control code, create a class with static function control()
Note: You cannot call the widget's method from callbackDispatcher!
Reason: Widgets are UI bound. As long as the screen remains active, the widget that is visible remains active. Once you close the app or move on to next screen, the widgets' memory gets recycled. But this callbackDispatcher gets executed even when your app is closed. So, it has to be isolated from UI code.
Here's the code:
main.dart:
import 'package:flutter/material.dart';
import 'package:workmanager/workmanager.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
runApp(App());
}
void callbackDispatcher() {
Workmanager.executeTask((taskName, inputData) async {
switch(taskName)
{
case ScheduledTask.taskName:
ScheduledTask.control(); // calls your control code
break;
}
return Future.value(true);
});
}
class ScheduledTask {
const static String taskName = "control";
static void control() {
// add your control here
}
}
All you can do from HomeScreen widget is to call setupWorkManager() that schedules the task
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Container();
}
#override
void initState() {
super.initState();
setupWorkManager();
}
}
void setupWorkManager() async {
Workmanager.registerPeriodicTask(taskKontrol, taskKontrol,
frequency: Duration(minutes: 15),
existingWorkPolicy: ExistingWorkPolicy.append
);
}
Note: The minimum frequency for the recurring task is 15 minutes

Flutter throwing error when used the get method in the http package

When I am trying to get data from the internet to use it in my app via the get method provided by the flutter http package it throws this error - The argument type 'String' can't be assigned to the parameter type 'Uri'. This is my code
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class Loading extends StatefulWidget {
#override
_LoadingState createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
#override
void getData() async {
http.get("https://jsonplaceholder.typicode.com/todos/1")
}
void initState() {
super.initState();
getData();
}
Widget build(BuildContext context) {
return Scaffold(
body: Text("some text"),
);
}
}
First argument of http package request method is Uri type, So you have to change your code to this:
void getData() async {
final requestUrl = Uri.parse("https://jsonplaceholder.typicode.com/todos/1");
http.get(requestUrl)
}

How to ensure code is run only once in a widget?

I do have a lot of code that looks like
this:
bool _somethingFromApiLoaded = false;
Something _somethingFromApi;
loadSomething() async {
final something = await ServiceProvider.of(context).apiService.getSomething();
setState(() => _somethingFromApi = something);
}
#override
Widget build(BuildContext context) {
if (!_somethingFromApiLoaded) {
loadSomething();
_somethingFromApiLoaded = true;
}
}
Note how I produce a lot of boilerplate code to ensure loadSomething is only called once.
I wonder if there isn't a lifecycle method to do so that I somehow misinterpret. I can't use initState because it does not have context.
I would try to a use a StatefulWidget and use initState() method.
That is the lifecycle you are referring to.
You should try to use a Future inside the initState()
#override
void initState() {
super.initState(); // make sure this is called in the beggining
// your code here runs only once
Future.delayed(Duration.zero,() {
_somethingFromApi = await ServiceProvider.of(context).apiService.getSomething();
});
}
As User gegobyte said, Context is available in the initState.
But apparently can't be used for everything.
You can use context in initState() by passing it to the widget:
class HomeScreen extends StatefulWidget {
final BuildContext context;
HomeScreen(this.context);
#override
State<StatefulWidget> createState() => new _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool _somethingFromApiLoaded = false;
Something _somethingFromApi;
loadSomething() async {
final something = await ServiceProvider.of(widget.context).apiService.getSomething();
setState(() => _somethingFromApi = something);
}
#override
void initState() {
super.initState();
if (!_somethingFromApiLoaded) {
loadSomething();
_somethingFromApiLoaded = true;
}
}
}