1
votes

I am trying to make a slider to enlarge and reduce the font but I am facing this error.

E/flutter (11441): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'setString' was called on null.

E/flutter (11441): Receiver: null

E/flutter (11441): Tried calling: setString("fontSizeArabic", "23.99652777777778")

E/flutter (11441): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)

E/flutter (11441): #1 SettingsHelpers.fontSizeArabic (package:alquranalkareem/helper/settings_helpers.dart:20:17)

E/flutter (11441): #2 _QuranShowState._showTafseer.. (package:alquranalkareem/module/quran/show.dart:881:32)

E/flutter (11441): #3 _SliderState._handleChanged (package:flutter/src/material/slider.dart:453:14)

E/flutter (11441): #4 _RenderSlider._startInteraction (package:flutter/src/material/slider.dart:982:7)

E/flutter (11441): #5 _RenderSlider._handleTapDown (package:flutter/src/material/slider.dart:1031:50)

E/flutter (11441): #6
TapGestureRecognizer.handleTapDown. (package:flutter/src/gestures/tap.dart:463:51)

E/flutter (11441): #7 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)

E/flutter (11441): #8 TapGestureRecognizer.handleTapDown (package:flutter/src/gestures/tap.dart:463:11)

E/flutter (11441): #9 BaseTapGestureRecognizer._checkDown (package:flutter/src/gestures/tap.dart:256:5)

E/flutter (11441): #10 BaseTapGestureRecognizer.didExceedDeadline (package:flutter/src/gestures/tap.dart:227:5)

E/flutter (11441): #11
PrimaryPointerGestureRecognizer.didExceedDeadlineWithEvent (package:flutter/src/gestures/recognizer.dart:496:5)

E/flutter (11441): #12
PrimaryPointerGestureRecognizer.addAllowedPointer. (package:flutter/src/gestures/recognizer.dart:449:40)

E/flutter (11441): #13 _rootRun (dart:async/zone.dart:1122:38)

E/flutter (11441): #14 _CustomZone.run (dart:async/zone.dart:1023:19)

E/flutter (11441): #15 _CustomZone.runGuarded (dart:async/zone.dart:925:7)

E/flutter (11441): #16 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:965:23)

E/flutter (11441): #17 _rootRun (dart:async/zone.dart:1126:13)

E/flutter (11441): #18 _CustomZone.run (dart:async/zone.dart:1023:19)

E/flutter (11441): #19 _CustomZone.bindCallback. (dart:async/zone.dart:949:23)

E/flutter (11441): #20 Timer._createTimer. (dart:async-patch/timer_patch.dart:23:15)

E/flutter (11441): #21 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19)

E/flutter (11441): #22 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)

E/flutter (11441): #23 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)

Do you have a solution to the problem?

settings_helpers

import 'dart:convert';
import 'dart:ui';
import 'package:quiver/strings.dart';
import 'package:shared_preferences/shared_preferences.dart';


class SettingsHelpers {
  static SettingsHelpers _instance;

  static SettingsHelpers get instance {
    if (_instance == null) {
      _instance = SettingsHelpers();
    }
    return _instance;
  }

  SharedPreferences prefs;

  Future fontSizeArabic(double fontSize) async {
    await prefs.setString('fontSizeArabic', fontSize.toString());
  }

  static const double minFontSizeArabic = 22;

  double get getFontSizeArabic {
    String fontSizeString = prefs.getString('fontSizeArabic');
    return double.tryParse(fontSizeString ?? minFontSizeArabic.toString());
  }

  Future setLocale(Locale locale) async {
    var map = {
      'languageCode': locale.languageCode,
    };
    var json = jsonEncode(map);
    await prefs.setString('locale', json);
  }

  Locale getLocale() {
    var json = prefs.getString('locale');
    if (isBlank(json)) {
      return Locale('en');
    }
    var mapJson = jsonDecode(json);
    var locale = Locale(mapJson["languageCode"]);
    return locale;
  }

  Future init() async {
    prefs = await SharedPreferences.getInstance();
  }
}

_showTafseer

Widget _showTafseer(int pageNum) {
        TafseerRepository tafseerRepository = new TafseerRepository();
        return FutureBuilder<List<Ayat>>(
          future: tafseerRepository.getPageTafseer(pageNum),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              List<Ayat> ayat = snapshot.data;
              return Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Column(
                  children: <Widget>[
                    Container(
                      color: Theme.of(context).primaryColorLight,
                      child: Row(
                        children: <Widget>[
                          Slider(
                            min: SettingsHelpers.minFontSizeArabic,
                            max: maxFontSizeArabic,
                            value: fontSizeArabic,
                            activeColor: Theme.of(context).hoverColor,
                            inactiveColor: Theme.of(context).primaryColorDark,
                            onChanged: (double value) async {
                              await SettingsHelpers.instance
                                  .fontSizeArabic(value);
                              setState(
                                    () {
                                  fontSizeArabic = value;
                                },
                              );
                              _myEventBus.eventBus.fire(
                                FontSizeEvent()
                                  ..arabicFontSize = value
                              );
                            },
                          ),
                          Container(
                            decoration: BoxDecoration(
                                color: Theme.of(context).hoverColor,
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(5.0),
                                topRight: Radius.circular(5.0),
                                bottomLeft: Radius.circular(5.0),
                                bottomRight: Radius.circular(5.0),
                              )
                            ),
                            alignment: Alignment.center,
                            child: Padding(
                              padding: const EdgeInsets.all(4.0),
                              child: Text('${fontSizeArabic.toInt()}',
                                  style: TextStyle(
                                      fontSize: 20,
                                      color: Theme.of(context).primaryColorLight)),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
    //              width: 300.0,
                      height: 500.0,
                      child: ListView.builder(
                          itemCount: ayat.length,
                          itemBuilder: (context, position) {
                            Ayat aya = ayat[position];
                            List<String> tafseer = aya.tafsser.split("))");
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              children: <Widget>[
                                Container(
                                  decoration: BoxDecoration(
                                      color: Theme.of(context).backgroundColor,
                                      borderRadius: BorderRadius.only(
                                      topRight: Radius.circular(8.0),
                                      topLeft: Radius.circular(8.0)
                                    )
                                  ),
                                  child: Padding(
                                    padding: const EdgeInsets.all(4.0),
                                    child: Text(
                                      "﴿${tafseer.first}﴾",
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        fontFamily: "Uthmanic",
                                        fontWeight: FontWeight.w500,
                                        fontSize: fontSizeArabic
                                      ),
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(top: 16.0, bottom: 8.0),
                                  child: Text(
                                    "${tafseer.last.trim()}",
                                    textAlign: TextAlign.justify,
                                    style: TextStyle(
                                      color: Theme.of(context).hoverColor,
                                      fontFamily: 'naskh',
                                      fontWeight: FontWeight.w100,
                                      fontSize: fontSizeArabic
                                    ),
                                  ),
                                ),
                                Divider()
                              ],
                            );
                          }),
                    ),
                  ],
                ),
              );
            } else {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
          },
        );
      }
1

1 Answers

2
votes

I think the issue is with prefs not being properly initialized. Just try making your initialization simpler as below

I have used the factory design pattern. See this article to learn more about it.

Note that I used a simple floating button to trigger the action rather than the slider

class SettingsHelpers {

  SharedPreferences prefs;

  static final SettingsHelpers _instance = SettingsHelpers._internal();
  SettingsHelpers._internal(){
    _init();
  }

  factory SettingsHelpers() => _instance;

  void _init() async {
    prefs = await SharedPreferences.getInstance();
  }

  void fontSizeArabic(double fontSize) async {
   prefs.setString('fontSizeArabic', fontSize.toString());
  }

  static const double minFontSizeArabic = 22;

  double get getFontSizeArabic {
    String fontSizeString = prefs.getString('fontSizeArabic');
    return double.tryParse(fontSizeString ?? minFontSizeArabic.toString());
  }

  Future setLocale(Locale locale) async {
    var map = {
      'languageCode': locale.languageCode,
    };
    var json = jsonEncode(map);
    await prefs.setString('locale', json);
  }

  Locale getLocale() {
    var json = prefs.getString('locale');
    if (isBlank(json)) {
      return Locale('en');
    }
    var mapJson = jsonDecode(json);
    var locale = Locale(mapJson["languageCode"]);
    return locale;
  }

}

class SampleTest extends StatefulWidget {
  @override
  _SampleTestState createState() => _SampleTestState();
}

class _SampleTestState extends State<SampleTest> {
  double fontSizeArabic;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton:
          FloatingActionButton(child: Icon(Icons.add), onPressed: _onPressed),
    );
  }

  void _onPressed() async {
    double value = 18.0;
    SettingsHelpers().fontSizeArabic(value);
  }
}