Flutter How to listen variable from other class - flutter

I want to listen variable from other class in flutter, so always to know if the app has internet connection
I have the streamcontroller in checknetwork.dart and listen in home.dart
I dont get anything at print statement
CheckNetwork.dart
class NetworkCheck {
var streamController = StreamController();
Future<bool> check() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
streamController.sink.add(true);
streamController.close();
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
streamController.sink.add(true);
streamController.close();
return true;
}
return false;
}
dynamic checkInternet(Function func) {
check().then((internet) {
if (internet != null && internet) {
func(true);
}
else{
func(false);
}
});
}
}
Home.dart
class Home extends StatefulWidget {
const Home({Key key}) : super(key: key);
#override
HomeState createState() => HomeState();
}
class HomeState extends State<Home>{
Future _checkNetwork() async {
NetworkCheck networkcheck = NetworkCheck();
networkcheck.streamController.stream.listen((data) {
print('Got! $data');
});
}

You need to have a state management System to get the stream controller accessible to all classes and it would be the efficient way , but if you still want your current code to work than call check method of NetworkCheck class before listening to the Stream .
So modify your home.dart like this:
class Home extends StatefulWidget {
const Home({Key key}) : super(key: key);
#override
HomeState createState() => HomeState();
}
class HomeState extends State<Home>{
Future _checkNetwork() async {
NetworkCheck networkcheck = NetworkCheck();
//this will provide value in your stream.
networkcheck.check();
networkcheck.streamController.stream.listen((data) {
print('Got! $data');
});
}

Related

Flutter Reactive State

I define a model reactively with GetX and send this model reactively to the view with the help of StateMixin. But this variable I sent changes the main variable as well. How exactly does this happen and how can I fix it? In the example I gave below, when I change the id value, the id automatically changes in the rawMyModel model. But I don't want it to change.
detail_controller.dart
class DetailController extends GetxController with StateMixin<Rx<MyModel>> {
late final MyModel rawMyModel;
#override
void onInit() async {
super.onInit();
rawMyModel = (Get.arguments as MyModel);
change(Rx(rawMyModel), status: RxStatus.success());
}
void reset() {
change(Rx(rawMyModel), status: RxStatus.success());
}
}
detail_page.dart
class DetailPage extends GetView<DetailController> {
const DetailPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: controller.obx((Rx<MyModel>? myModel) => _buildBody(myModel: myModel!)),
);
}
Widget _buildBody({required Rx<MyModel> myModel}) {
print(myModel.value.toString());
myModel.update((val) => val.id = 5); // change
}
}

Riverpod is not updating UI widget on state change

main.dart
void main() {
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends ConsumerWidget {
MyApp({Key? key}) : super(key: key);
final _appProvider =
ChangeNotifierProvider<AppProvider>((ref) => AppProvider());
final _profileProvider = ChangeNotifierProvider<ProfileProvider>((ref) {
return ProfileProvider();
});
#override
Widget build(BuildContext context, WidgetRef ref) {
AppProvider appProvider = ref.watch(_appProvider);
ProfileProvider profileManager = ref.watch(_profileProvider);
print(appProvider.appLocale);
}
appProvider.dart
class AppProvider extends ChangeNotifier {
Locale? _appLocale = const Locale('en');
Locale get appLocale => _appLocale ?? const Locale("en");
static const supportedLanguage = [Locale('en', 'US'), Locale('km', 'KH')];
void changeLanguage(Locale type) async {
_appLocale = type;
notifyListeners();
}
}
// when i log value of _appLocale here , I can see the update value based on the state change. but it does not re render UI widgeet.
I fixed it by declaring global provider, remove any deplicated provider, same name, in other files.

How to find a controller using GetX in flutter

I am trying to use Get.find to use LessonListController, but flutter tells me error,
throw '"$S" not found. You need to call "Get.put($S())" or "Get.lazyPut(()=>$S())"'
below is Lessonlistcontroller
class LessonListController extends GetxService {
final LessonListRepo lessonListRepo;
LessonListController({required this.lessonListRepo});
List<dynamic> _lessonList = [];
List<dynamic> get lessonList => _lessonList;
Future<void> getLessonList() async {
Response response = await lessonListRepo.getLessonList();
if (response.statusCode == 200) {
print('got you');
_lessonList = [];
_lessonList.addAll(Course.fromJson(response.body).lessons);
// update();
//update
} else {}
}
}
dependencies as below,
Future<void> init() async {
//api client
Get.lazyPut(() => ApiClient(appBaseUrl: AppConstants.BASE_URL));
//repos
Get.lazyPut(() => LessonListRepo(apiClient: Get.find()));
//controllers
Get.lazyPut(() => LessonListController(lessonListRepo: Get.find()));
}
here is the main.dart file
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
Get.find<LessonListController>().getLessonList();
// Get.lazyPut<LessonListController>(() =>get.() {
// };
return const GetMaterialApp(
debugShowCheckedModeBanner: false,
home: Diary(),
);
}
}
Thank you very much.
You haven't initialized the LessonListController using Get.put(LessonListController());
Get.find() is used to get the already initialized instance of Created controller.
GetxControlled works as Singleton, So it finds the already created instance every time you call Get.find() , Get.find() will only work if you have previously called Get.put or Get.lazyPut

Flutter LocalStorage returns null even after await storage.ready

I am trying to load a string from LocalStorage in flutter to set the theme accordingly but it returns null, even after await storage.ready in an async function. Here is the code example:
import 'package:localstorage/localstorage.dart';
final storage = LocalStorage('theming.json');
void main() async {
await storage.ready;
runApp(const UniversalConverter());
}
class UniversalConverter extends StatefulWidget {
const UniversalConverter({Key? key}) : super(key: key);
#override
_UniversalConverter createState() => _UniversalConverter();
}
class _UniversalConverter extends State<UniversalConverter> {
#override
Widget build(BuildContext context) {
final savedTheme = storage.getItem("theme");
ThemeMode selectedThemeMode = appThemes[0].mode;
switch (savedTheme) {
case null:
selectedThemeMode = appThemes[0].mode;
storage.setItem("theme", "light");
print("Theme Preference not found; Setting Light Mode by Default!");
break;
case 'light':
selectedThemeMode = appThemes[0].mode;
print("Light Mode");
break;
case 'dark':
selectedThemeMode = appThemes[1].mode;
print("Dark Mode");
break;
case 'system':
selectedThemeMode = appThemes[2].mode;
print("System Mode");
}
The code continues... this is the problematic part.
Any help would be appreciated!
Thanks :)

sign out function flutter using sharedpreferences

I need a little help about signing out using shared preferences.
I got here functional code snippet which is from the MainMenu class.
class MainMenu extends StatefulWidget {
final VoidCallback signOut;
MainMenu(this.signOut);
#override
_MainMenuState createState() => _MainMenuState();
}
class _MainMenuState extends State<MainMenu> {
int index = 0;
List<Widget> list = [
HomeScreen(),
Stations(),
AccountPage(),
];
signOut() {
setState(() {
widget.signOut();
});
}
I want it to be transfered or be called in my other class which is here. MyDrawer class.
class MyDrawer extends StatefulWidget {
final Function onTap;
MyDrawer(
{this.onTap
});
#override
_MyDrawerState createState() => _MyDrawerState();
}
class _MyDrawerState extends State<MyDrawer> {
And this code snippet where I saved the prefrences of the signOut().
signOut() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
preferences.setInt("value", null);
preferences.setString("fname", null);
preferences.setString("lname", null);
preferences.setString("email", null);
preferences.setString("address", null);
preferences.setString("mobile", null);
preferences.setString("date", null);
preferences.setString("id", null);
preferences.commit();
_loginStatus = LoginStatus.notSignIn;
});
}
I have also made a switch case for the login status.
switch (_loginStatus) {
case LoginStatus.notSignIn:
return Scaffold(
break;
case LoginStatus.signIn:
return MainMenu(signOut);
break;
What I want is to get the access of signOut method in my MyDrawer class. Thanks in advance.