I am still a beginner and while writing some simple app with dart , this problem appeared , the vs code studio does not show any errors within the code but the app won't run on the device and shows a red screen with this written :
NoSuchMethodError
The method 'map' was called on null.
Receiver: null
Tried calling: map(Closure: (String) => Answer)
.....
here is the code :
import 'package:flutter/material.dart';
import './questions.dart';
import './Answer.dart';
//void main() {
//runApp(MyCoolApp());
//}
void main() => runApp(
MyCoolApp());
class MyCoolApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyCoolAppState();
}
}
class _MyCoolAppState extends State<MyCoolApp> {
var _questionsIndex = 0;
void _answerQuestions() {
setState(() {
_questionsIndex = _questionsIndex + 1;
});
print(_questionsIndex);
}
#override
Widget build(BuildContext context) {
const questions = const [
{
'questionText': 'what is your favorite animal?',
'asnwers': ['Black', 'White', 'Green', 'yellow'],
},
{
'questionText': 'what is your favorite food?l?',
'asnwers': ['MONKEY', 'LION', 'ELEPHANT', 'GIRAFFE'],
},
{
'questionText': 'what is your favorite music genre?',
'answers': ['ROCK', 'CLASSIC', 'JAZZ', 'COUNTRY']
}
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(
'7AMADA APP',
style: TextStyle(
color: Colors.black,
),
),
),
body: Column(
children: [
Questions(
questions.elementAt(_questionsIndex)['questionText'],
),
...(questions.elementAt(_questionsIndex)['answers'] as List<String>)
.map((answer) {
return Answer(_answerQuestions, answer);
}).toList()
],
),
),
);
}
}
Related
I want to check for internet connection at every screen on my app just like Telegram does and whenever user goes offline, show an Offline banner on the top of the screen.
I have tried using connectivity_plus and internet_connection_checker plugins to check for this but the problem is I have to subscribe to a stream for this and if the device goes offline once then there is no way to subscribe to it again without clicking a button.
getConnectivity() =>
subscription = Connectivity().onConnectivityChanged.listen(
(ConnectivityResult result) async {
isDeviceConnected = await InternetConnectionChecker().hasConnection;
if (!isDeviceConnected && isAlertSet == false) {
setState(() {
constants.offline = true;
print('Constants().offline ${constants.offline}');
isAlertSet = true;
});
}
print('off');
},
);
I'm using this code right now to check this issue but I don't want to replicate this code on each and every screen and even if I do replicate it then there will be a lot of subscriptions that I'll be subscribing to, which will mean that all the subscriptions will be disposed at the same time causing all sorts of issues.
If you have custom Scaffold, then you have to edit it. Otherwise, create a new one and change all Scaffolds to your custom one. This allows you to easily apply changes that should be on all pages.
Then, in the CustomScaffold create a Stack that contains page content and ValueListenableBuilder that listens to connection changes and if there is no internet displays error banner.
class CustomScaffold extends StatefulWidget {
const CustomScaffold({Key? key}) : super(key: key);
#override
State<CustomScaffold> createState() => _CustomScaffoldState();
}
class _CustomScaffoldState extends State<CustomScaffold> with WidgetsBindingObserver {
StreamSubscription? connectivitySubscription;
ValueNotifier<bool> isNetworkDisabled = ValueNotifier(false);
void _checkCurrentNetworkState() {
Connectivity().checkConnectivity().then((connectivityResult) {
isNetworkDisabled.value = connectivityResult == ConnectivityResult.none;
});
}
initStateFunc() {
_checkCurrentNetworkState();
connectivitySubscription = Connectivity().onConnectivityChanged.listen(
(ConnectivityResult result) {
isNetworkDisabled.value = result == ConnectivityResult.none;
},
);
}
#override
void initState() {
WidgetsBinding.instance.addObserver(this);
initStateFunc();
super.initState();
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if (state == AppLifecycleState.resumed) {
_checkCurrentNetworkState();
}
}
#override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
connectivitySubscription?.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.expand,
children: [
Scaffold(
...
),
ValueListenableBuilder(
valueListenable: isNetworkDisabled,
builder: (_, bool networkDisabled, __) =>
Visibility(
visible: networkDisabled,
child: YourErrorBanner(),
),
),
],
);
}
}
First I created an abstract class called BaseScreenWidget
used bloc state management to listen each time the internet connection changed then show toast or show upper banner with Blocbuilder
abstract class BaseScreenWidget extends StatelessWidget {
const BaseScreenWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Column(
children: [
baseBuild(context),
BlocConsumer<InternetConnectionBloc, InternetConnectionState>(
listener: (context, state) {
// if (!state.isConnected) {
// showToast("No Internet Connection");
// }
},
builder: (context, state) {
if (!state.isConnected) {
return const NoInternetWidget();
}
return const SizedBox.shrink();
},
),
],
);
}
Widget baseBuild(BuildContext context);
}
Made each screen only screen widgets contains Scaffold to extends BaseScreenWidget
class MainScreen extends BaseScreenWidget {
const MainScreen({super.key});
#override
Widget baseBuild(BuildContext context) {
return const Scaffold(
body: MainScreenBody(),
);
}
}
it's very helpful to wrap the Column with SafeArea in the build method in BaseScreen.
USE THIS SIMPLE TECHNIQUE only need this package: Internet Connection Checker. If you turn off your network it will tell you
connection_checker.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
class CheckMyConnection {
static bool isConnect = false;
static bool isInit = false;
static hasConnection(
{required void Function() hasConnection,
required void Function() noConnection}) async {
Timer.periodic(const Duration(seconds: 1), (_) async {
isConnect = await InternetConnectionChecker().hasConnection;
if (isInit == false && isConnect == true) {
isInit = true;
hasConnection.call();
} else if (isInit == true && isConnect == false) {
isInit = false;
noConnection.call();
}
});
}
}
base.dart
import 'package:flutter/material.dart';
import 'connection_checker.dart';
class Base extends StatefulWidget {
final String title;
const Base({Key? key, required this.title}) : super(key: key);
#override
State<Base> createState() => _BaseState();
}
class _BaseState extends State<Base> {
final snackBar1 = SnackBar(
content: const Text(
'Internet Connected',
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.green,
);
final snackBar2 = SnackBar(
content: const Text(
'No Internet Connection',
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.red,
);
#override
void initState() {
super.initState();
CheckMyConnection.hasConnection(hasConnection: () {
ScaffoldMessenger.of(navigatorKey.currentContext!)
.showSnackBar(snackBar1);
}, noConnection: () {
ScaffoldMessenger.of(navigatorKey.currentContext!)
.showSnackBar(snackBar2);
});
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
key: navigatorKey,
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
title: const Text('Tabs Demo'),
),
body: const TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
);
}
}
I myself use connectivity_plus and I have never found the problem you mentioned (if the device goes offline once then there is no way to subscribe to it again without clicking a button), you can use my example.
If the user's internet is disconnected, a modal will appear. If the user is connected again, the modal will be deleted automatically.
Anyway, I put the option to check the internet again in the modal
class CheckConnectionStream extends GetxController {
bool isModalEnable = false;
final loadingCheckConnectivity = false.obs;
ConnectivityResult _connectionStatus = ConnectivityResult.none;
final Connectivity _connectivity = Connectivity();
late StreamSubscription<ConnectivityResult> _connectivitySubscription;
Future<void> initConnectivity() async {
late ConnectivityResult result;
try {
result = await _connectivity.checkConnectivity();
loadingCheckConnectivity.value = false;
} on PlatformException {
return;
}
return _updateConnectionStatus(result);
}
Future<void> _updateConnectionStatus(ConnectivityResult result) async {
_connectionStatus = result;
if (result == ConnectivityResult.none) {
if (isModalEnable != true) {
isModalEnable = true;
showDialogIfNotConnect();
}
} else {
if (isModalEnable) {
Get.back();
}
isModalEnable = false;
}
}
showDialogIfNotConnect() {
Get.defaultDialog(
barrierDismissible: false,
title: "check your network".tr,
onWillPop: () async {
return false;
},
middleText: "Your device is not currently connected to the Internet".tr,
titleStyle: TextStyle(
color: Get.isDarkMode ? Colors.white : Colors.black,
),
middleTextStyle: TextStyle(
color: Get.isDarkMode ? Colors.white : Colors.black,
),
radius: 30,
actions: [
Obx(() => loadingCheckConnectivity.value
? const CustomLoading(
height: 30.0,
radius: 30.0,
)
: ElevatedButton(
onPressed: () async {
loadingCheckConnectivity.value = true;
EasyDebounce.debounce(
'check connectivity',
const Duration(milliseconds: 1000), () async {
await initConnectivity();
});
},
child: Text(
'try again'.tr,
style: const TextStyle(color: Colors.white),
),
))
]);
}
#override
void onInit() {
super.onInit();
initConnectivity();
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
}
#override
void onClose() {
_connectivitySubscription.cancel();
super.onClose();
}
}
I am trying to implement invoking Flutter Code From Native Side using method channel and working as expected. But having issue with rendering the view after trying to set the state. Can any one help to fix the issue?
Actually the SimSlotInfo is calling from the below widget,
List<Step> getSteps() {
return <Step>[
Step(
state: currentStep > 0 ? StepState.complete : StepState.indexed,
isActive: currentStep >= 0,
title: const Text("Send SMS"),
content: Column(
children: [
SimSlotInfo()
],
),
),
];
}
SimSlotInfo dart class
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutterdemo/model/device_slot.dart';
class SimSlotInfo extends StatefulWidget {
//callback function
final void Function(String) callBackFunction;
const SimSlotInfo(this.callBackFunction, {super.key});
//const SimSlotInfo({Key? key}) : super(key: key);
#override
State<SimSlotInfo> createState() => _SimSlotInfoState();
}
class _SimSlotInfoState extends State<SimSlotInfo> {
final platformMethodChannel = const MethodChannel('common_lib_plugin');
List<SimDetails> simDetailsObj = [];
//execute the below code while page loading
#override
void initState() {
super.initState();
platformMethodChannel.setMethodCallHandler(handleNativeMethodCall);
}
Future<void> handleNativeMethodCall(MethodCall call) async {
// do some processing
switch(call.method) {
case "deviceInfo":
var simData = call.arguments;
var arrayObjsText = '[{"slot":0,"simno":"89911017061","deviceid":"3518920","carrierName":"Vodafone"},{"slot":1,"simno":"89101706","deviceid":"3511643","carrierName":"JIO"}]';
List simObjsJson = jsonDecode(arrayObjsText) as List;
simDetailsObj = simObjsJson.map((tagJson) => SimDetails.fromJson(tagJson)).toList();
setState(() {
simDetailsObj = simDetailsObj;
});
}
}
#override
Widget build(BuildContext context) {
return Column(
children:
simDetailsObj.map((data) => RadioListTile(
dense: true,
contentPadding: EdgeInsets.zero,
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"${data.carrierName}",
style: const TextStyle(color: Colors.black, fontSize: 18),
),
],
),
groupValue: _selectedSim,
value: data.simno,
onChanged: (val) {
},
)).toList()
);
}
}
First, you are trying to assign List to List so your code is getting brake there. to solve that loop the object with SimDetails object. and that will do the trick
ParentWidget
class _ParentWidgetState extends State<ParentWidget> {
#override
Widget build(BuildContext context) {
return ChildWidget( // <---- child widget
callSetState: (list) { // <--- callback Function
print(list);
setState(() {
// <---
});
},
);
}
}
In Child widget
class ChildWidget extends StatefulWidget {
const ChildWidget({Key? key, required this.callSetState}) : super(key: key);
final Function(List<SimDetails>) callSetState; // <-- declare callback function here
#override
State<ChildWidget> createState() => _ChildWidgetState();
}
and replace your setState with widget.callSetState
Future<void> handleNativeMethodCall(MethodCall methodCall) async {
switch (call.method) {
case 'deviceInfo':
var simData = call.arguments;
var arrayObjsText =
'[{"slot":0,"simno":"89911017061","deviceid":"3518920","carrierName":"Vodafone"},{"slot":1,"simno":"89101706","deviceid":"3511643","carrierName":"JIO"}]';
for (var data in jsonDecode(arrayObjsText)) {
simDetailsObj.add(
SimDetails(
slot: data['slot'],
simno: data['simno'],
deviceid: data['deviceid'],
carrierName: data['carrierName'],
),
);
}
/// setState(() {});
widget.callSetState(simDetailsObj);
break;
default:
}}
I am new to Flutter. I am building a quiz app and have the following three dart files:
main.dart
import 'package:flutter/material.dart';
import './answer.dart';
import './question.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatefulWidget {
State<StatefulWidget> createState(){
return _MyAppState();
}
}
class _MyAppState extends State<MyApp>{
var _questionIndex = 0;
_answerQuestion(){
setState(() {
_questionIndex = _questionIndex + 1;
});
}
#override
Widget build(BuildContext context) {
var questions = [
{'questionText': 'What\'s your favourite color ?',
'answers': ['Red','Blue','White','Black']
},
{'questionText': 'What\'s your favourite Animal ?',
'answers': ['Dog','Rabbit','Tiger','Monkey']
},
{'questionText': 'What\'s your favourite Day ?',
'answers': ['Tuesday','Monday','Sunday','Friday','Wednesday','Saturday']
},
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question(questions[_questionIndex]['questionText'] as String,
),
...(questions[_questionIndex]['answers'] as List).map((answer) {
return Answer(_answerQuestion(),answer);
}).toList()
],
)
),
);
}
}
question.dart
import 'package:flutter/material.dart';
class Question extends StatelessWidget {
final String questions;
Question(this.questions);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child:(
Text(
questions,
style: TextStyle(
fontSize: 25),
textAlign: TextAlign.center,)
),
);
}
}
answer.dart
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final Function buttonHandler;
final String answer;
Answer(this.buttonHandler,this.answer);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text(answer),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue),
foregroundColor: MaterialStateProperty.all(Colors.white)
),
onPressed: () => buttonHandler,
),
);
}
}
when I run the application on my android in Android studio, I get this error:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY╞═══════════════════════════════════════════
The following _TypeError was thrown building MyApp(dirty, state: _MyAppState#7f7de):
type 'Null' is not a subtype of type 'Function'
The relevant error-causing widget was:
MyApp file:///C:/src/first_app/lib/main.dart:7:10
This:
onPressed: () => buttonHandler,
needs to be either:
onPressed: buttonHandler,
or
onPressed: () => buttonHandler(),
depending on whether your handler matches the required signature exactly.
In addition, this:
return Answer(_answerQuestion(),answer);
needs to be
return Answer(_answerQuestion,answer);
Generally speaking, you have mixed up calling a method and passing a method as a parameter a few times, you may want to get more familiar with it.
First, you must pass a function structure instead returning value from the function by calling it.
You declared this function below:
_answerQuestion(){
setState(() {
_questionIndex = _questionIndex + 1;
});
}
and passed the return value instead of function structure like below:
return Answer(_answerQuestion(),answer);
As you can see the return value of _answerQuestion() is Null.
Change your code like this.
return Answer(_answerQuestion,answer);
And you need to call the funcion in the Answer component.
onPressed: buttonHandler
or
onPressed: () => buttonHandler()
Your code is working fine try flutter clean
hope you doin' well
I'm a newbie to flutter and I'm working on a basic weather app as a starter. now, somehow everything is okay, except the city name. I don't know how to implement city search feature and get data from api based on the location. In my code, I defined city name manually.
here is my code:
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:hava_chitor/Carousel.dart';
import 'package:hava_chitor/UnderCarousel.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var temp;
var name;
var humidity;
var description;
var city = 'London';
CarouselController buttonCarouselController = CarouselController();
Future getWeather() async {
http.Response response = await http.get(
"http://api.openweathermap.org/data/2.5/weather?q=$city&units=metric&appid=apikey");
var results = jsonDecode(response.body);
setState(() {
this.temp = results['main']['temp'];
this.name = results['name'];
this.humidity = results['main']['humidity'];
this.description = results['weather'][0]['main'];
});
}
#override
void initState() {
super.initState();
this.getWeather();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hava Chitor?',
theme: ThemeData(
primaryColor: Color(0xff424242),
),
home: Scaffold(
drawer: Drawer(),
appBar: AppBar(
actions: [
Padding(
padding: const EdgeInsets.all(15),
child: GestureDetector(
onTap: () {
print('kir');
},
child: Icon(
Icons.add_circle_outline,
color: Color(0xff5d5f64),
),
),
)
],
backgroundColor: Colors.transparent,
elevation: 0,
iconTheme: IconThemeData(color: Color(0xff5d5f64)),
title: Text(
'Hava Chitor?',
style: TextStyle(
color: Color(0xff5d5f64),
fontFamily: 'Sans',
fontWeight: FontWeight.w700),
),
centerTitle: true,
),
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 1.0),
child: Column(
children: [
Carousel(name),
UnderCarousel(temp, description, humidity),
],
),
),
),
);
}
}
you need to add a TextField and a TextFieldController and call the function getWeather when the user finish writing the city name, something like this
String city;
TextEditingController textEditingController = TextEditingController();
TextField(
controller: textEditingController,
onSubmitted: (value){
city = textEditingController.text;
getWeather();
},
),
what you need to do is add TextField for the user to input the city name.
the way you can do that is shown before. The next thing you have to do is write a function to fetch weather data with city name.
var url =
'http://api.openweathermap.org/data/2.5/weather?q=\$city&units=metric&appid=apikey';
class CityWeatherData {
final String city, temprateure, humidity; //...
CityWeatherData({
this.city,
this.temprateure,
this.humidity,
// ...
});
factory CityWeatherData.fromJson(Map<String, dynamic> json) {
return CityWeatherData(
city: json['city'],
humidity: json['city']['humidity'],
temprateure: json['city']['temp'],
// ...
);
}
}
Future<CityWeatherData> fetchWeatherDataBycity() async {
final response = await http.get(url);
if (response.statusCode == 200) {
return CityWeatherData.fromJson(jsonDecode(response.body));
} else {
throw Exception('failed to fetch data.');
}
}
I depending on the JSON data you get you have to edit the fromjson method.
I hope this was helpful!
I am new to Flutter. I want to get the text along with its source. Currently, I am using receive_sharing_intent which is serving the purpose of TextStream and Url individually.
I want to share the copied text from the browser and keep its URL along with it.
I followed this doc hence my main.dart is same as:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
StreamSubscription _intentDataStreamSubscription;
List<SharedMediaFile> _sharedFiles;
String _sharedText;
#override
void initState() {
super.initState();
// For sharing or opening urls/text coming from outside the app while the app is in the memory
_intentDataStreamSubscription =
ReceiveSharingIntent.getTextStream().listen((String value) {
setState(() {
_sharedText = value;
});
}, onError: (err) {
print("getLinkStream error: $err");
});
// For sharing or opening urls/text coming from outside the app while the app is closed
ReceiveSharingIntent.getInitialText().then((String value) {
setState(() {
_sharedText = value;
});
});
}
#override
void dispose() {
_intentDataStreamSubscription.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
const textStyleBold = const TextStyle(fontWeight: FontWeight.bold);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text("Shared files:", style: textStyleBold),
Text(_sharedFiles?.map((f)=> f.path)?.join(",") ?? ""),
SizedBox(height: 100),
Text("Shared urls/text:", style: textStyleBold),
Text(_sharedText ?? "")
],
),
),
),
);
}
}
Any suggestions on how to proceed to this or any Reference will work.
Thanks!!